import { message } from '@/utils/message'
import type { PaginationProps } from '@pureadmin/table'
import { ModalShowType } from '@/types/common'
import { reactive, ref, computed, onMounted, toRaw } from 'vue'
import { columnWidthConfig } from '@/config/table'
import { commonExportListToExcel } from '@/api/common'
import { omitEmptyValue } from '@/utils/common'
import { getAppList } from '@/api/app-list/app-list'
import { useRouter } from 'vue-router'
import { deleteApp } from '@/api/api-manage/list'
import useDictStore from '@/store/modules/dict'

export function useData() {
  const router = useRouter()
  const form = reactive({
    ids: [],
    appName: '',
    searchValue: '',
    createByName: '',
    startDate: null,
    endDate: null,
    // status: ""
  })
  const dataList = ref([])
  const loading = ref(true)
  const termId = ref<string>()
  const modalShow = ref(ModalShowType.Hide)
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
  })

  const { app_type } = useDictStore().getDicts('app_type')

  const showSelection = false // 控制是否展示选择列
  const columns: TableColumnList = [
    {
      type: 'selection',
      width: columnWidthConfig.checkbox,
      align: 'left',
    },
    {
      label: '应用名称',
      prop: 'appName',
      minWidth: columnWidthConfig.projectName,
    },
    {
      label: '应用属性',
      prop: 'appAttribute',
      minWidth: columnWidthConfig.projectNumber,
      formatter: ({ appAttribute }) => app_type.getLabel(appAttribute),
    },
    {
      label: '归属部门',
      prop: 'deptName',
      minWidth: 150,
    },
    {
      label: '发布时间',
      prop: 'publishTime',
      minWidth: 120,
    },
    {
      label: '应用联系人',
      prop: 'appContact',
      minWidth: 120,
    },
    {
      label: '联系人电话',
      prop: 'appContactPhone',
      minWidth: 150,
    },
    {
      label: '更多',
      prop: 'type',
      fixed: 'right',
      minWidth: 150,
      cellRenderer: ({ row, ..._props }) => (
        <div class="flex align-middle justify-around">
          <div
            class="text-blue-400 cursor-pointer"
            onClick={() => {
              router.push({
                path: '/app-manage/detail',
                query: { id: row.appId },
              })
              // termId.value = row.appId;
              // modalShow.value = ModalShowType.View;
            }}
          >
            应用详情
          </div>
          {/* {hasAuth("pm:costMgt:update") && (
            <div
              class="text-blue-400 cursor-pointer"
              onClick={() => {
                modalShow.value = ModalShowType.Edit;
                termId.value = row.costId;
              }}
            >
              编辑
            </div>
          )} */}
        </div>
      ),
    },
  ]

  const buttonClass = computed(() => {
    return [
      '!h-[20px]',
      'reset-margin',
      '!text-gray-500',
      'dark:!text-white',
      'dark:hover:!text-primary',
    ]
  })

  function handleUpdate(row) {
    console.log(row)
  }

  async function handleDelete(data) {
    // await deleteReport(costId);
    await deleteApp(data)
    message('删除成功', { type: 'success' })
    await onSearch()
  }

  async function handleSizeChange(val: number) {
    console.log(`${val} items per page`)
    await onSearch(pagination.currentPage, val)
  }

  async function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`)
    await onSearch(val, pagination.pageSize)
  }

  const selectedRows = ref([])
  function handleSelectionChange(val) {
    selectedRows.value = val
    form.ids = val.map((item) => item.costId)
  }

  async function onSearch(pageNum = 1, pageSize = 10) {
    loading.value = true
    const data = await getAppList({
      ...omitEmptyValue(toRaw(form)),
      pageNum,
      pageSize,
    })

    dataList.value = data.rows
    pagination.currentPage = pageNum
    pagination.pageSize = pageSize
    pagination.total = data.total
    setTimeout(() => {
      loading.value = false
    }, 500)
  }

  const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
    onSearch()
  }

  const statusDict = ref<Map<number, string>>(new Map())

  // onMounted(async () => {
  //   Promise.all([getDicts("report_status_value"), onSearch()]).then(res => {
  //     statusDict.value = res[0];
  //   });
  // });
  onMounted(onSearch)

  async function onExportData() {
    commonExportListToExcel('/pm/costMgt/export', {
      ...omitEmptyValue(toRaw(form)),
      // params: {
      //   ids: selectedRows.value.map(item => item.costId).join(",") || [],
      //   // searchValue: form.searchValue
      // }
    })
  }

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    showSelection,
    buttonClass,
    statusDict,
    modalShow,
    termId,
    selectedRows,
    onSearch,
    resetForm,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    onExportData,
  }
}
